package com.stylefeng.guns.core.intercept;

import org.springframework.stereotype.Component;
import org.springframework.web.filter.HiddenHttpMethodFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Component
public class MyHiddenHttpMethodFilter  extends HiddenHttpMethodFilter{
    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
            throws ServletException, IOException {
        String header=request.getParameter("_header");
        if (header!=null && !header.trim().equals("")) {
            HttpServletRequest wrapper = new HttpHeaderRequestWrapper(request,header);
            super.doFilterInternal(wrapper, response, filterChain);
        }else {
            super.doFilterInternal(request, response, filterChain);
        }
    }

    private static class HttpHeaderRequestWrapper extends HttpServletRequestWrapper {

        private final String header;

        public HttpHeaderRequestWrapper(HttpServletRequest request,String licence) {
            super(request);
            this.header=licence;
        }

        @Override
        public String getHeader(String name) {
            if (name!=null &&
                    name.equals("Accept") &&
                    super.getHeader("Accept")==null) {
                return header;
            }else {
                return super.getHeader(name);
            }
        }

    }
}
